package com.sxfq.loansupermarket.backsystem.modular.IntegralMall.service.Impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.sun.org.apache.regexp.internal.RE;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.dao.MemberProductDao;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.service.MemberProductService;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.VipLevelInfo;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.CaseInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.entity.PerformanceInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.entity.RechargeInfo;
import com.sxfq.loansupermarket.backsystem.modular.weixin.service.IWxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class MemberProductServiceImpl implements MemberProductService {
    @Autowired
    IWxService wxService;

    @Autowired
    private MemberProductDao dao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SqlMapper sqlMapper;

    @Override
    public List<PointRewordInfo> selectPageListByQueryGetMap(Page<PointRewordInfo> page, SearchPointRewordInfo searchInfo) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", page);
        if (StringUtil.isNotEmpty(searchInfo.getStatus())) {
            params.put("status", searchInfo.getStatus());
        }
        if (StringUtil.isNotEmpty(searchInfo.getPhone())) {
            params.put("phone", searchInfo.getPhone());
        }
        if (StringUtil.isNotEmpty(searchInfo.getStartCreateTime())) {
            params.put("startCreateTime", searchInfo.getStartCreateTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndCreateTime())) {
            params.put("endCreateTime", searchInfo.getEndCreateTime());
        }
        params.put("startIndex", searchInfo.getStartIndex());
        params.put("limitIndex", searchInfo.getLimitIndex());
        return dao.getQueryPage(page, params);
    }

    @Override
    public int getQueryPagesMemberCount(Page<PointRewordInfo> page, SearchPointRewordInfo searchInfo) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", page);
        if (StringUtil.isNotEmpty(searchInfo.getStatus())) {
            params.put("status", searchInfo.getStatus());
        }
        if (StringUtil.isNotEmpty(searchInfo.getPhone())) {
            params.put("phone", searchInfo.getPhone());
        }
        if (StringUtil.isNotEmpty(searchInfo.getStartCreateTime())) {
            params.put("startCreateTime", searchInfo.getStartCreateTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndCreateTime())) {
            params.put("endCreateTime", searchInfo.getEndCreateTime());
        }
        return dao.getQueryPagesMemberCounts(page, params);
    }

    public PointRewordInfo selectOneById(String id) {
        String sql = "select * from point_reword_info where id= '" + id + "' limit 1";
        PointRewordInfo info = sqlMapper.selectOne(sql, PointRewordInfo.class);
        return info;
    }

    public List<Map<String, Object>> list() {
        String sql = "select * from point_reword_info order by create_time asc;";
        return sqlMapper.selectList(sql);
    }

    public int sendAppointmentMessage(String openId, String treatmentUnit, String projectData, String doctor, String reservationsNum,
                                      String customerName, String startTimeValue, String reservationsId, String customerPhone) {
        wxService.sendAppointmentMessage(openId, treatmentUnit, projectData, doctor, reservationsNum, customerName, startTimeValue, reservationsId, customerPhone);
        return 1;
    }

    public int updateConfigIp(int shopid, String deptip) {
        String sql = "update dept set deptip='" + deptip + "' where id=" + shopid + ";";
        return sqlMapper.update(sql);
    }

    public String queryDeptIpByid(String shopid) {
        String sql = "select id,deptip,simplename,abbreviation from dept where id='" + shopid + "' limit 1";
        MembersAssistInfo membersAssistInfo = sqlMapper.selectOne(sql, MembersAssistInfo.class);
        return membersAssistInfo.getDeptip();
    }

    public CaseInfo questionnaire(String caseid) {
        String sql="select id from satisfaction_survey a where a.case_id='"+caseid+"' limit 1";
        CaseInfo caseInfo=sqlMapper.selectOne(sql,CaseInfo.class);
        return caseInfo;
    }

    public int insertMembertable(String abbreviation, MembersArriveInfo membersArriveInfo) {
        String sql = "INSERT INTO `member_distinguish_info` (`reservations_id`, `medical_record_number`, `member_name`, `member_phone`, " +
                "`member_age`, `member_sex`, `avatar`, `feature`, `quality`) VALUES " +
                "('" + membersArriveInfo.getReservationsId() + "','" + membersArriveInfo.getMedicalRecordNumber() + "', '" + membersArriveInfo.getMemberName() + "'," +
                " '" + membersArriveInfo.getMemberPhone() + "', " + membersArriveInfo.getMemberAge() + ", " + membersArriveInfo.getMemberSex() + ", " +
                " '" + membersArriveInfo.getAvatar() + "', '" + membersArriveInfo.getFeature() + "', '" + membersArriveInfo.getQuality() + "');";
        return sqlMapper.insert(sql);
    }

    public List<MembersDistinguishInfo> memberSync() {
        String sql = "select * from member_distinguish_info a group by reservations_id order by grasp_time desc";
        List<MembersDistinguishInfo> MembersUserList = sqlMapper.selectList(sql, MembersDistinguishInfo.class);
        return MembersUserList;
    }

    public int updateMemberFeature(String reservationsId, String feature, String quality) {
        String sql = "update member_distinguish_info a set a.feature='" + feature + "',a.quality='" + quality + "' where a.reservations_id='" + reservationsId + "'";
        return sqlMapper.update(sql);
    }

    public int sendMedicalAdviceMessage(String openId, String doctor, String medicalAdviceTitle, String content) {
        wxService.sendMedicalAdviceMessage(openId, doctor, medicalAdviceTitle, content);
        return 1;
    }

    public String getVipLevelName(String reservationsId) {
        String sql = "select * from "+ redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"vip_level_info",0) +" a order by money";
        List<VipLevelInfo> vipLevelInfoList = sqlMapper.selectList(sql, VipLevelInfo.class);
        String abbreviationSql = "select abbreviation from distinction_customer_status where reservations_id = '" + reservationsId + "' and status=1";
        List<String> abbreviationList = sqlMapper.selectList(abbreviationSql, String.class);
        if (abbreviationList == null) {
            return vipLevelInfoList.get(0).getVipLevelName();
        }
        String rechargeTables = "select if(sum(hospitalPerformance) is null,0,sum(hospitalPerformance)) as hospitalPerformance from (";
        for (int i = 0; i < abbreviationList.size(); i++) {
            String head = abbreviationList.get(i);
            if (i == abbreviationList.size() - 1) {
                rechargeTables += " select a.hospital_performance as hospitalPerformance from " + head + "recharge_info a where a.reservations_id='" + reservationsId + "' ";
            } else {
                rechargeTables += " select a.hospital_performance as hospitalPerformance from " + head + "recharge_info a where a.reservations_id='" + reservationsId + "' union all ";
            }
        }
        rechargeTables += ") t";
        PerformanceInfo performanceInfo = sqlMapper.selectOne(rechargeTables, PerformanceInfo.class);
        String vipLevelName = "";
        if (performanceInfo == null) {
            return vipLevelInfoList.get(0).getVipLevelName();
        }
        if (performanceInfo.getHospitalPerformance() >= vipLevelInfoList.get(vipLevelInfoList.size() - 1).getMoney()) {
            vipLevelName = vipLevelInfoList.get(vipLevelInfoList.size() - 1).getVipLevelName();
        } else {
            for (int i = 0; i < vipLevelInfoList.size(); i++) {
                if (performanceInfo.getHospitalPerformance() >= vipLevelInfoList.get(i).getMoney() &&
                        performanceInfo.getHospitalPerformance() < vipLevelInfoList.get(i + 1).getMoney()) {
                    vipLevelName = vipLevelInfoList.get(i).getVipLevelName();
                    break;
                }
            }
        }
        return vipLevelName;
    }

    public VipLevelInfo getVipLevelTest(String reservationsId) {
        String sql = "select * from "+ redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"vip_level_info",0) +" a order by money";
        List<VipLevelInfo> vipLevelInfoList = sqlMapper.selectList(sql, VipLevelInfo.class);
        String abbreviationSql = "select abbreviation from distinction_customer_status where reservations_id = '" + reservationsId + "' and status=1";
        List<String> abbreviationList = sqlMapper.selectList(abbreviationSql, String.class);
        if (abbreviationList == null) {
            return null;
        }
        String rechargeTables = "select if(sum(hospitalPerformance) is null,0,sum(hospitalPerformance)) as hospitalPerformance from (";
        for (int i = 0; i < abbreviationList.size(); i++) {
            String head = abbreviationList.get(i);
            if (i == abbreviationList.size() - 1) {
                rechargeTables += " select a.hospital_performance as hospitalPerformance from " + head + "recharge_info a where a.reservations_id='" + reservationsId + "' ";
            } else {
                rechargeTables += " select a.hospital_performance as hospitalPerformance from " + head + "recharge_info a where a.reservations_id='" + reservationsId + "' union all ";
            }
        }
        rechargeTables += ") t";
        PerformanceInfo performanceInfo = sqlMapper.selectOne(rechargeTables, PerformanceInfo.class);
        String vipLevelName = "入门会员";
        if (performanceInfo == null) {
            String sesql = "select * from "+ redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"vip_level_info",0) +" a where vip_level_name='" + vipLevelName + "' limit 1";
            VipLevelInfo vipLevelInfo = sqlMapper.selectOne(sesql, VipLevelInfo.class);
            return vipLevelInfo;
        }
        if (performanceInfo.getHospitalPerformance() >= vipLevelInfoList.get(vipLevelInfoList.size() - 1).getMoney()) {
            vipLevelName = vipLevelInfoList.get(vipLevelInfoList.size() - 1).getVipLevelName();
        } else {
            for (int i = 0; i < vipLevelInfoList.size(); i++) {
                if (performanceInfo.getHospitalPerformance() >= vipLevelInfoList.get(i).getMoney() &&
                        performanceInfo.getHospitalPerformance() < vipLevelInfoList.get(i + 1).getMoney()) {
                    vipLevelName = vipLevelInfoList.get(i).getVipLevelName();
                    break;
                }
            }
        }
        String sesql = "select * from "+ redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"vip_level_info",0) +" a where vip_level_name='" + vipLevelName + "' limit 1";
        VipLevelInfo vipLevelInfo = sqlMapper.selectOne(sesql, VipLevelInfo.class);
        return vipLevelInfo;
    }

    public VipLevelInfo getVipLevel(String reservationsId) {
        String sql = "select ifnull(sum(actual_account_balance),0) as moneyBalance from reservemoney_deal " +
                "where reservations_id = '" + reservationsId + "' and mode!='消费' ";
        CustomerInfo info=sqlMapper.selectOne(sql, CustomerInfo.class);
        String sql2 = "select * from "+ redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"vip_level_info",0) +" a ";
        List<VipLevelInfo> infov = sqlMapper.selectList(sql2, VipLevelInfo.class);
        for (VipLevelInfo iv:infov) {
            if (iv.getMoneyCoefficientTwo() > info.getMoneyBalance() && info.getMoneyBalance() >= iv.getMoneyCoefficient()) {
                String sesql = "select * from "+ redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"vip_level_info",0) +" a where vip_level_name='" + iv.getVipLevelName() + "' limit 1";
                VipLevelInfo vipLevelInfo = sqlMapper.selectOne(sesql, VipLevelInfo.class);
                return vipLevelInfo;
            }
        }
        String sesql = "select * from "+ redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"vip_level_info",0) +" a where vip_level_name='入门会员' limit 1";
        VipLevelInfo vipLevelInfo = sqlMapper.selectOne(sesql, VipLevelInfo.class);
        return vipLevelInfo;
    }
    public VipLevelInfo getVipLevel101(String reservationsId) {
        String sql = "select * from "+ redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"vip_level_info",0) +" a order by money";
        List<VipLevelInfo> vipLevelInfoList = sqlMapper.selectList(sql, VipLevelInfo.class);
        String abbreviationSql = "select abbreviation from distinction_customer_status where reservations_id = '" + reservationsId + "' and status=1";
        List<String> abbreviationList = sqlMapper.selectList(abbreviationSql, String.class);
        if (abbreviationList == null) {
            return null;
        }
        String rechargeTables = "select if(sum(hospitalPerformance) is null,0,sum(hospitalPerformance)) as hospitalPerformance from (";
        for (int i = 0; i < abbreviationList.size(); i++) {
            String head = abbreviationList.get(i);
            if (i == abbreviationList.size() - 1) {
                rechargeTables += " select a.hospital_performance as hospitalPerformance from " +
                        "" + head + "recharge_info a left join " + head + "deal_info b " +
                        " on a.deal_id=b.id where a.reservations_id='" + reservationsId + "' " +
                        " and left(a.recharge_time,10)>='2019-10-01' and b.operation_time is null ";
            } else {
                rechargeTables += " select a.hospital_performance as hospitalPerformance from " +
                        "" + head + "recharge_info a left join " + head + "deal_info b" +
                        " on a.deal_id=b.id where a.reservations_id='" + reservationsId + "'" +
                        " and left(a.recharge_time,10)>='2019-10-01' and b.operation_time is null union all ";
            }
        }
        rechargeTables += ") t";
        PerformanceInfo performanceInfo = sqlMapper.selectOne(rechargeTables, PerformanceInfo.class);
        String vipLevelName = "入门会员";
        if (performanceInfo == null) {
            String sesql = "select * from "+ redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"vip_level_info",0) +" a where vip_level_name='" + vipLevelName + "' limit 1";
            VipLevelInfo vipLevelInfo = sqlMapper.selectOne(sesql, VipLevelInfo.class);
            return vipLevelInfo;
        }
        if (performanceInfo.getHospitalPerformance() >= vipLevelInfoList.get(vipLevelInfoList.size() - 1).getMoney()) {
            vipLevelName = vipLevelInfoList.get(vipLevelInfoList.size() - 1).getVipLevelName();
        } else {
            for (int i = 0; i < vipLevelInfoList.size(); i++) {
                if (performanceInfo.getHospitalPerformance() >= vipLevelInfoList.get(i).getMoney() &&
                        performanceInfo.getHospitalPerformance() < vipLevelInfoList.get(i + 1).getMoney()) {
                    vipLevelName = vipLevelInfoList.get(i).getVipLevelName();
                    break;
                }
            }
        }
        String sesql = "select * from "+ redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"vip_level_info",0) +" a where vip_level_name='" + vipLevelName + "' limit 1";
        VipLevelInfo vipLevelInfo = sqlMapper.selectOne(sesql, VipLevelInfo.class);
        return vipLevelInfo;
    }
}